#include <stdio.h>
#include "Hw3Types.h"
#include "Hw3TypesExtended.h"
#include "GlobalVariables.h"
#include "SyncAndProtectionModule.h"
#include "Output.h"

// internal function Declarations
BOOL CompareFaces(TFace *FirstFace, TFace *SecondFace);
int Abs(int x);
//End of Function Declarations


BOOL CompareFaceToFacebook(TFace *FaceToCompare)
{
	// variable declerations
	TFace *CurrentFace=NULL; 

	// for debug mode
	#ifdef DEBUG_MODE_VERBOSE
		printf("Starting to compare face at (%d, %d) with faces in Facebook", FaceToCompare->Box.OriginX, FaceToCompare->Box.OriginY);
	#endif

	// make sure there is more than one face in the facebook
	if (FaceToCompare->NextFace != NULL)
	{
		// start going over the faces in facebook
		TFace *CurrentFace = FaceToCompare->NextFace;
		while (NULL != CurrentFace)
		{
			// check that the program should still be running
			if (IsProgramTerminated())
				return FALSE;
			// compare the faces
			if (CompareFaces(FaceToCompare, CurrentFace) == TRUE)
			{
				// if a matching face was found, try writing it to the end file. If this failed,
				// it means an error has occured earlier and we should not write anything to the 
				// output file.
				if (WriteEndFile("Identical faces found!") == TRUE)
				{
					// we write to the output file only if an error hasn't been discovered first
					WriteOutputFile(FaceToCompare, CurrentFace);
					return TRUE;
				}
			}
			CurrentFace = CurrentFace->NextFace;	
		} 
	}
	
	// in case no matching face was found, return FALSE
	return FALSE;
}


//Internal Functions
BOOL CompareFaces(TFace *FirstFace, TFace *SecondFace)
{
	// variable declerations
	int i,j,x1,y1,x2,y2;
	int Difference;
	int Offpixel = 0; //this will count the number of "off pixels" between the two faces
	
	// for debug mode 
	#ifdef DEBUG_MODE_VERBOSE
		printf("Starting to compare face at (%d, %d) with face at (%d, %d)\n", FirstFace->Box.OriginX, FirstFace->Box.OriginY, SecondFace->Box.OriginX, SecondFace->Box.OriginY);
	#endif

	// go over each pixel in the faces and compare
	for (i = 0 ; i < FaceSize.Height ; i++)
	{
		y1 = FirstFace->Box.OriginY + i;
		y2 = SecondFace->Box.OriginY + i;
		for(j=0; j < FaceSize.Width ; j++)
		{
			x1 = FirstFace->Box.OriginX + j;
			x2 = SecondFace->Box.OriginX + j;
			Difference = Abs(Image[y1][x1] - Image[y2][x2]);
			if ((Difference <= 50) && (Difference != 0))
			{
				Offpixel++;
				// if the number of offpixels is bigger than the maximum - the faces are not identical
				if (Offpixel > MaximumNumberOfOffPixels)
					return FALSE;
			}
			else if (Difference > 50)
				return FALSE;
		}
	}
	return TRUE;
}

// return the absolute value of an integer
int Abs(int x)
{
	return (x>=0 ? x : -x);
}

//End of Internal Functions